package com.example.kt_common.network

import android.util.Log
import com.blankj.utilcode.util.LogUtils
import com.example.kt_common.util.Constants
import com.example.kt_common.util.KVUtil
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Created by 小陈 on 2025/3/23.
 * Time: 16:04.
 */
object RetrofitManager {
    val TAG = this.javaClass.simpleName;

    //    private const val BASE_URL = "https://www.wanandroid.com/"
//    private const val BASE_URL = "http://119.13.85.137:2031"; //香港环境
    private const val BASE_URL = "http://47.112.224.58:9003"; //大陆环境
    private var retrofit: Retrofit

    init {
        // 创建用于添加请求头的拦截器
        val addHeaderInterceptor = Interceptor { chain ->
            val originalRequest = chain.request()
            Log.i(TAG, "发送请求method:--oldRequest->" + originalRequest.method)
            Log.i(TAG, "发送请求url:-----oldRequest->" + originalRequest.url)
            Log.i(TAG, "发送请求method:--newRequest->" + originalRequest.method)
            Log.i(TAG, "发送请求url:-----newRequest->" + originalRequest.url + "")
            Log.i(TAG, "发送请求headers:--newRequest->" + originalRequest.headers + "")
            Log.i(TAG, "发送请求headers:--KVUtil.getString(Constants.TOKEN)->" + KVUtil.getString(Constants.TOKEN) + "")

            // 构建新的请求，并添加自定义的请求头
            val newRequest = originalRequest.newBuilder()
//                .addHeader("Custom-Header-1", "HeaderValue1") // 添加自定义请求头
//                .addHeader("Custom-Header-2", "HeaderValue2") // 可以添加多个请求头
                .addHeader("token", KVUtil.getString(Constants.TOKEN)?:"") // 可以添加多个请求头
                .build()
            // 继续处理请求
            chain.proceed(newRequest)


        }
        // 创建日志拦截器
        val loggingInterceptor = HttpLoggingInterceptor {
            LogUtils.d(TAG, "OkHttp Log--> : $it")
        }.setLevel(HttpLoggingInterceptor.Level.BODY)
        val okHttpClient = OkHttpClient().newBuilder().callTimeout(10, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS).retryOnConnectionFailure(true)
            .followRedirects(false).cookieJar(MyCookieJar())
            .addInterceptor(loggingInterceptor)
            .addInterceptor(addHeaderInterceptor)
            .build()
        retrofit = Retrofit.Builder().client(okHttpClient).baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create()).build()

    }

    fun <T> getService(service: Class<T>): T {
        return retrofit.create(service)
    }
}